<template>
	<view class="chart">
		<view class="chart-title">
			<t-icon name="chevron-left" size="26" @click="onBack" />
			<view class="chart-title-center">
				<text class="chart-title-center-main">{{ currItem.qqdx }}支撑群</text>
				<text class="chart-title-center-sub">{{ currItem.zzmc }}&nbsp;{{ currItem.cjrmc }}发起</text>
			</view>
			<t-icon name="ellipsis" size="26" @click="onChartInfo" />
			<!-- <view>
				<t-icon name="user-add" size="26" @click="onPersonAdd" />
				<t-icon name="ellipsis" size="26" @click="onChartInfo" />
			</view> -->
		</view>
		<view class="chart-list">
			<view class="chart-list-item" v-for="item, index in chartList" :key="index">
				<view v-if="isShowChartTime(item, index)" class="chart-list-item-tip tip-time">{{ item.cjsj }}</view>
				<!-- 0 提示信息、 1 文字、2语音、3图片、4文件 -->
				<view v-if="item.ltlx == 0" class="chart-list-item-tip">{{ item.nrxx }}</view>
				<view v-else class="chart-list-item-main" :class="{ 'my-item': item.mjjh == 302871 }">
					<view class="chart-list-item-main-avatar">{{ item.mjmc }}</view>
					<view class="chart-list-item-main-warp" :class="{ 'my-warp': item.mjjh == 302871 }">
						<text class="chart-list-item-main-info">{{ item.zzmc }}&nbsp;{{ item.mjjh }}</text>
						<view class="chart-list-item-main-content">
              <view v-if="item.ltlx == 2" class="type-audio" @click="playAudio(item.nrxx)">
								<t-icon name="wifi" size="26" style="transform: rotate(90deg);"></t-icon>
								<text>播放语音</text>
							</view>
							<t-image v-if="item.ltlx == 3" class="type-img" :src="item.nrxx" fit="scale-down" lazy @click="showImgViewer = true"></t-image>
							<view v-else-if="item.ltlx == 4" class="type-extra" @click.stop="onDownload(item)">
								<image class="type-extra-icon" src="@/static/images/file.png" mode="aspectFit" />	
								<view class="type-extra-main">
									<view class="type-extra-main-title">{{ JSON.parse(item.nrxx).name }}</view>
									<view class="type-extra-main-sub">{{ JSON.parse(item.nrxx).size }}</view>
								</view>
							</view>
							<text v-if="item.ltlx == 1" v-html="item.nrxx"></text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<t-image-viewer v-model:images="allImgList" v-model:visible="showImgViewer" />
		<t-input class="chart-input" v-model="inputValue" :disabled="isTalk" :align="isTalk ? 'center' : 'left'">
			<template #prefixIcon>
        <transition name="fade" mode="out-in">
				<t-icon v-if="!isTalk" name="sonic" size="26" @click="onChangeInputOrTalk('talk')"></t-icon>
				<t-icon v-else name="keyboard" size="26" @click="onChangeInputOrTalk('input')"></t-icon>
      </transition>
				<!-- <t-icon name="add" size="26" @click="onStopTalk"></t-icon> -->
			</template>
			<template #suffix>
				<text class="icon-at" @click="showAtPopup = true">@</text>
				<t-icon name="add-circle" size="26" @click="onMore"></t-icon>
			</template>
		</t-input>
		<view ref="chartMoreRef" class="chart-more" :style="showMore ? 'height: 150px; padding: 16px 14px;' : 'height: 0;'" tabindex="0" @blur="onMoreBlur">
			<view class="chart-more-warp" v-show="showMore">
				<view class="chart-more-item" @click="onUpload('img')">
					<view class="chart-more-item-icon"><t-icon name="image" size="26"></t-icon></view>
					<text>图片</text>
				</view>
				<view class="chart-more-item" @click="onUpload('file')">
					<view class="chart-more-item-icon"><t-icon name="folder-open-1" size="26"></t-icon></view>
					<text>文件</text>
				</view>
			</view>
		</view>
    <t-popup v-model="showAtPopup" placement="bottom" closeBtn>
      <PersonList title="@人员" mode="at" @onAddAt="onAddAt" />
    </t-popup>
	</view>
</template>

<script setup>
	import { onLoad } from '@dcloudio/uni-app';
	import { Message } from 'tdesign-mobile-vue';
	import { computed, ref } from 'vue';
  import PersonList from "@/components/PersonList"
	
	onLoad(async options => {
		// console.log('465465465465465465465');
		// uni.$message.success('成公222');
		// console.log(JSON.stringify({ name: '文本文件.text', size: '32KB' }));
		// console.log(JSON.stringify({ name: '文档.doc', size: '2MB' }));
		if (!options.qqId) {
			Message['error']({ offset: [10, 16], content: '缺失请求id', icon: true });
			return;
		}
		initTalk();
		await updateCurrItem(options.qqId);
		getChartLsit();
	});
	
	const currItem = ref({});
	const inputValue = ref('');
	const chartMoreRef = ref();
	const showMore = ref(false);
	const showImgViewer = ref(false);
	const chartList = ref([]);
  const innerAudioContext = ref(null);
  const showAtPopup = ref(false);
  const isTalk = ref(false);

	// 录音
	const isWeb = window && window.MediaRecorder && (uni.getSystemInfoSync().uniPlatform == 'web' || uni.getSystemInfoSync().uniPlatform == 'h5');
	const recorderManager = ref(null);
	const tempFilePath = ref('');
	const mediaRecorder = ref(null);
	const chunks = ref([]);
	const audioBlob = ref(null);
	const audioSrc = ref('');
  const duration = ref(0); // 新增：用于存储录音时长
  let startTime = 0; // 记录录音开始时间
	
	const allImgList = computed(() => chartList.value.filter(item => item.ltlx == 3).map(item => item.nrxx));
	const isShowChartTime = computed(() => (item, index) => {
		if (index == 0) return true;
		return new Date(item.cjsj) - new Date(chartList.value[index - 1].cjsj) > 1 * 60 * 1000; // 一分钟内不显示
	})
	
	const updateCurrItem = qqId => {
		return new Promise(resolve => {
			currItem.value = {
				id: qqId,
				ltsbh: 'chart1',
				ztzt: 2,
				ztnr: '一标三实',
				qqdx: '基础管控中心',
				cjrmc: '熊倡',
				zzmc: '科信科',
				cjrlxdh: '17358486814',
				qqsj: '2025-03-10 10:07:01',
				jjcd: '系统',
				nrms: '一标三实数据不一致，请仔细核查。一标三实数据不一致，请仔细核查。一标三实数据不一致，请仔细核查。一标三实数据不一致，请仔细核查。'
			}
			resolve();
		})
	}
	
	const getChartLsit = () => {
		chartList.value = [
			{ ltlx: 0, nrxx: '熊倡加入了群聊', isMe: 2, cjsj: '2025-01-15 17:05:47', mjjh: '302871', mjmc: '熊倡', zzmc: '科信科' },
      { ltlx: 1, nrxx: currItem.value.nrms, isMe: 2, cjsj: '2025-01-15 17:05:47', mjjh: '302871', mjmc: '熊倡熊', zzmc: '科信科' },
			{ ltlx: 1, nrxx: '什么问题', isMe: 2, cjsj: '2025-01-15 17:05:59', mjjh: '302100', mjmc: '张俊', zzmc: '基础管控中心' },
      { ltlx: 1, nrxx: currItem.value.ztnr, isMe: 1, cjsj: '2025-01-15 17:07:47', mjjh: '302871', mjmc: '熊倡', zzmc: '科信科' },
      { ltlx: 2, nrxx: 'https://st.92kk.com/2025/%E4%B8%B2%E7%83%A7%E8%88%9E%E6%9B%B2/202501/20250116/%E4%B8%9C%E8%8E%9EDj%E6%96%B0%E4%BB%94_%E5%85%A8%E5%9B%BD%E8%AF%ADFunkyHouse%E9%9F%B3%E4%B9%90%E5%B7%B4%E5%B7%B4%E7%9A%84%E8%B4%9D%E5%92%9A%E5%92%9A%E8%BD%A6%E8%BD%BD%E4%B8%B2%E7%83%A7.mp3', isMe: 1, cjsj: '2025-01-15 18:07:30', mjjh: '302871', mjmc: '熊倡', zzmc: '科信科' },
      { ltlx: 2, nrxx: 'https://st.92kk.com/2025/%E4%B8%B2%E7%83%A7%E8%88%9E%E6%9B%B2/202501/20250116/%E4%B8%9C%E8%8E%9EDj%E6%96%B0%E4%BB%94_%E5%85%A8%E5%9B%BD%E8%AF%ADFunkyHouse%E9%9F%B3%E4%B9%90%E5%B7%B4%E5%B7%B4%E7%9A%84%E8%B4%9D%E5%92%9A%E5%92%9A%E8%BD%A6%E8%BD%BD%E4%B8%B2%E7%83%A7.mp3', url: '', isMe: 2, cjsj: '2025-01-15 18:10:30', mjjh: '302871', mjmc: '熊倡', zzmc: '科信科' },
      { ltlx: 3, nrxx: 'https://wx2.sinaimg.cn/mw690/62e8078fgy1hs58fpn4zsj21jk2bcn96.jpg', url: '', isMe: 2, cjsj: '2025-01-15 18:11:30', mjjh: '302871', mjmc: '熊倡', zzmc: '科信科' },
      { ltlx: 3, nrxx: 'https://wx1.sinaimg.cn/mw690/005GKY8ily1hgobmgl2htj31jk11011x.jpg', url: '', isMe: 1, cjsj: '2025-01-15 18:11:32', mjjh: '302100', mjmc: '张俊', zzmc: '基础管控中心' },
      { ltlx: 4, nrxx: '{"name":"文本文件.text","size":"32KB"}', url: '', fileName: '500105710000104.jpg', fileSize: '12.9KB',isMe: 2, cjsj: '2025-01-15 17:11:30', mjjh: '302871', mjmc: '熊倡', zzmc: '科信科' },
      { ltlx: 4, nrxx: '{"name":"文档.doc","size":"2MB"}', url: '', fileName: '500105710000104.jpg', fileSize: '12.9KB', isMe: 1, cjsj: '2025-01-15 18:11:32', mjjh: '302100', mjmc: '张俊', zzmc: '基础管控中心' },
		]
	}
	
	const onPersonAdd = () => {
		Message['success']({ offset: [10, 16], content: '人员邀请', icon: true });
	}

  const playAudio = (url) => {
		// innerAudioContext.value.pause();
    if (innerAudioContext.value) {
      innerAudioContext.value.destroy();
    }
    innerAudioContext.value = uni.createInnerAudioContext();
    innerAudioContext.value.src = url;
    innerAudioContext.value.play();
    innerAudioContext.value.onPlay(() => {
      console.log('开始播放');
    });
    innerAudioContext.value.onError((res) => {
      console.log(res.errMsg);
      console.log(res.errCode);
    });
  };
	
	const onChartInfo = () => {
		// 置顶聊天：后端新增一个置顶时间字段, 如果有值,那么按照时间倒序排
		// Message['success']({ offset: [10, 16], content: '基本信息、人员列表、操作日志Tab栏切换呈现', icon: true });
		uni.navigateTo({ url: `/pages/more/index?qqId=${currItem.value.id}`, animationType: 'slide-in-right' });
	}

  const onChangeInputOrTalk = type => {
    isTalk.value = type;
    if (type == 'talk') inputValue.value = '按住说话';
    else inputValue.value = '';
  }
	
	const initTalk = () => {
		uni.$message.success(`isWeb：${isWeb}`);
		if (isWeb) {
			navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {
				mediaRecorder.value = new MediaRecorder(stream);
				mediaRecorder.value.ondataavailable = e => chunks.value.push(e.data);
        mediaRecorder.value.onstart = () => {
          startTime = Date.now(); // 记录开始时间
        };
				mediaRecorder.value.onstop = () => {
					audioBlob.value = new Blob(chunks.value, { type: 'audio/mp3' });
					audioSrc.value = URL.createObjectURL(audioBlob.value);
          duration.value = Math.floor((Date.now() - startTime) / 1000); // 计算时长
          playAudio(audioSrc.value);
					console.log('录音完成，音频blob:', audioBlob.value, audioSrc.value, `${duration.value}秒`);
				};
			}).catch(err => {
        uni.$message.error(`获取录音权限失败`, );
        console.error('获取录音权限失败:', err)
      });
		} else {
			recorderManager.value = uni.getRecorderManager();
			recorderManager.value.onStop((res) => {
				tempFilePath.value = res.tempFilePath;
        duration.value = res.duration; // 小程序等平台直接提供时长
				console.log('录音文件临时路径:', tempFilePath.value);
			});
		}
	}
	
	const onTalk = () => {
		if (isWeb) {
			if (mediaRecorder.value) {
				chunks.value = [];
				mediaRecorder.value.start();
			}
		} else {
			recorderManager.value.start({
				duration: 60000, // 最大时长1分钟
				sampleRate: 16000,
				numberOfChannels: 1,
				encodeBitRate: 96000,
				format: 'mp3',
				frameSize: 50,
			});
		}
		uni.$message.success('录音开始');
    
		// uni.$message.success('语音222');
		// Message['success']({ offset: [10, 16], content: '语音', icon: true });
	}
	
	const onStopTalk = () => {
		if (isWeb) mediaRecorder.value && mediaRecorder.value.stop();
		else recorderManager.value.stop();
		uni.$message.success('录音结束');
	}
	
	const onUpload = type => {
		Message['success']({ offset: [10, 16], content: '上传' + type, icon: true });
	}

  const onAddAt = item => {
    Message['success']({ offset: [10, 16], content: item.mjmc, icon: true });
  }
	
	const onMore = () => {
		showMore.value = true;
		chartMoreRef.value.$el.focus();
	}
	
	const onMoreBlur = () => {
		showMore.value = false;
	}
	
	const onBack = () => {
		uni.navigateBack();
	}
</script>

<style lang="scss" scoped>
.chart {
	width: 100%;
	height: 100vh;
	display: flex;
	flex-direction: column;
	// background-color: #f2f3f7;
	background-color: #fafbff;
	
	&-title {
		height: 72px;
		position: relative;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12px;
		background-color: #fff;
		border-bottom-left-radius: 12px;
		border-bottom-right-radius: 12px;
		box-shadow: 0px 6px 12px 0px rgba(#2A7AFF, 5%);
		
		&-center {
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
			display: flex;
			flex-direction: column;
			justify-content: center;
			row-gap: 4px;
			
			&-main {
				font-weight: 500;
				font-size: 18px;
				text-align: center;
			}
			
			&-sub {
				font-size: 14px;
				color: #666666;
				text-align: center;
			}
		}
	}
	
	&-list {
		flex: 1;
		overflow-x: hidden;
		overflow-y: auto;
		padding: 12px;
		display: flex;
		flex-direction: column;
		row-gap: 14px;
		// border: 1px solid orchid;
		
		&-item {
			display: flex;
			flex-direction: column;
			width: 100%;
			// margin-bottom: 6px;
			font-size: 14px;
			
			&-tip {
				color: #999999;
				font-size: 13px;
				margin: 0 auto;
				margin-bottom: 0px;
				padding: 4px 8px;
				border-radius: 6px;
				// background-color: rgba(#205186, 0.1);

				&.tip-time {
					margin-bottom: 12px;
				}
			}
			
			&-main {
				display: flex;
				column-gap: 12px;
				
				&.my-item {
					flex-direction: row-reverse;
					
					button {
						color: #bbdcff;
					}

					.chart-list-item-main-content {
						color: #fff;
						background-color: var(--td-brand-color);
						
						&:has(.type-img) {
							background-color: transparent;
						}
					}

					.type-extra-main-title {
						color: #fff;
					}

					.type-extra-main-sub {
						color: #e0e0e0;
					}
				}
				
				&-avatar {
					width: 42px;
					height: 42px;
					display: flex;
					justify-content: center;
					align-items: center;
					word-break: keep-all;
					font-size: 13px;
					border-radius: 50%;
					color: #fff;
					// background-color: rgba(#4676cc, 0.8);
					background-color: var(--td-brand-color);
				}
				
				&-warp {
					display: flex;
					flex-direction: column;
					align-items: flex-start;
					row-gap: 4px;
					max-width: 50%;
					
					&.my-warp {
						align-items: flex-end;
					}
				}
				
				&-info {
					color: #999999;
					font-size: 13px;
				}
				
				&-content {
					display: flex;
					align-items: center;
					border-radius: 6px;
					padding: 10px;
					color: #333;
					// background-color: #F6F9FF;
					background-color: #f3f3f3;
					overflow: hidden;
					line-height: 1.5;
					font-size: 15px;
					
					&:has(.type-img) {
						background-color: transparent;
					}

          .type-audio {
						display: flex;
						align-items: center;
						column-gap: 8px;
						cursor: pointer;
					}
					
					.type-img {
						width: 150px;
						border-radius: 6px;
					}
					
					.type-extra {
						display: flex;
						align-items: center;

						&-icon {
							width: 38px;
							height: 38px;
						}

						&-main {
							width: 120px;
							height: 100%;
							margin-left: 12px;

							&-title {
								margin: 0;
								color: #333;
								font-weight: normal;
								margin-bottom: 4px;
							}

							&-sub {
								color: #9e9e9e;
								font-size: 13px;
							}
						}
					}
				}
			}
		}
	}
	
	&-input {
		// position: fixed;
		// left: 0;
		// bottom: 0;
		width: 100%;
		border-top-left-radius: 12px;
		border-top-right-radius: 12px;
		box-shadow: 0px -6px 12px 0px rgba(#2A7AFF, 5%);
		// background-color: red;
		background-color: #fff;
		
		.icon-at {
			font-weight: 500;
			font-size: 26px;
			margin-right: 8px;
		}
		
		&.t-input {
			flex: none;
		}

    :deep(.t-input__control--disabled) {
      color: var(--td-input-default-text-color, var(--td-text-color-primary, var(--td-font-gray-1, rgba(0, 0, 0, 0.9))))
    }
    
		
		:deep(.t-input__icon--prefix) {
			align-items: center;
		}
		
		:deep(.t-input__icon--prefix:not(:empty) + .t-input__label:empty) {
			margin-right: 12px;
		}
		
		:deep(.t-input__control) {
			background-color: #f6f6f6;
			height: 38px;
			border-radius: 8px;
			padding: 6px 10px;
		}
	}
	
	&-more {
		background-color: #fff;
		width: 100%;
		transition: height 0.3s;
		
		&:focus {
			outline: none;
		}
		
		&-warp {
			width: 100%;
			height: 100%;
			display: grid;
			grid-template-columns: repeat(4, 1fr);
			gap: 12px;
		}
		
		&-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			row-gap: 6px;
			font-size: 14px;
			
			&-icon {
				background-color: #f6f6f6;
				border-radius: 12px;
				padding: 14px;
			}
		}
	}
}
</style>